﻿var OTP_sequence = 0;
var OTP_pad = "sFIHWFefIHQ3Rqjdiaehf#WR"; //TODO: Randomize this!
var OTP_salt = "sadgjbawrugbovawrb"; //TODO: Randomize this!
var requestRetries = 0;

//---------------------------------------------------
// Things to do when document is rendered complete
//---------------------------------------------------
document.onreadystatechange = function() {
  if (document.readyState == "complete") {
    System.Gadget.settingsUI = "Settings.html";
    System.Gadget.onSettingsClosed = settingsClosed;
  }
}

//---------------------------------------------------
// Settings page closed event
//---------------------------------------------------
function settingsClosed(event) {
  if (event.closeAction == event.Action.commit) {
    // $("#background").fadeOut("slow", function() {
    GetProfile();
    // });
  }
}

//---------------------------------------------------
// Call the JSON page for getting the actual profile 
//---------------------------------------------------
function GetProfile() {

  // Get the User id from the saved setttings
  var userId = System.Gadget.Settings.read("userId");

  // Get the site from the saved settings
  var password = System.Gadget.Settings.read("password");

  // Show the init help text and bail out if no user id was found
  if (userId == "") {
    $("#background").css("visibility", "hidden");
    $("#firstpage").fadeIn("slow");
    return;
  }
  else {
    $("#firstpage").fadeOut("slow");

    // Build the JSON query URL
	var queryURL = "http://api2.sofurry.com/std/getUserProfile";
	var queryParameters = addOTPParameters(new array(), userId, password);
	
	requestRetries = 0;
	$.getJSON(queryURL, queryParameters, profileCallback);

//	$.ajax({
//	    dataType: 'text',
//	    success: profileCallback,
//	    url: "http://localhost.localdomain/index.php?r=std/getUserProfile&id=" + userId
//	});

    $("#background").css("visibility", "visible");
    $("#background").fadeIn(1500, function() {

    });
  }

  // Poll the site every 5 minutes
  setTimeout("GetProfile()", 1000 * 300); // 1000 * 300 = 5min.
}

function addOTPParameters(requestParameters, username, password) {
	requestParameters['otpuser'] = username;
	var hashedPassword = MD5(password + OTP_salt);
	var hash = MD5(hashedPassword + OTP_pad + OTP_sequence);
	requestParameters['otphash'] = hash;
	requestParameters['otpsequence'] = OTP_sequence;
	return requestParameters;
}


//--------------------------------------------
// Populate the page with the retrieved data
//--------------------------------------------
function profileCallback(data) {
//	vbsMsgBox(data.userID, 16, "Debug");
//	var data = $.parseJSON(text);

	//We received new encryption credentials from the OTP service, so resend the request using the new data
	if (data.messageType != undefined && data.messageType == 6) {
		OTP_sequence = data.newSequence;
		OTP_pad = data.newPadding;
		OTP_salt = data.salt;
		var userId = System.Gadget.Settings.read("userId");
		var password = System.Gadget.Settings.read("password");
		var queryURL = "http://api2.sofurry.com/std/getUserProfile";
		var queryParameters = addOTPParameters(new array(), userId, password);
		$("#avatar").empty();
		requestRetries++;
		if (requestRetries > 5) {
			$("#avatar").append("Error!");
			return;
		}
		$("#avatar").append("Retrying...");
		$.getJSON(queryURL, queryParameters, profileCallback);
		return;
	}
	// Avatar
	$("#avatar").empty();
	$("#avatar").append("<img src=\"http://www.sofurry.com/std/avatar?user="+data.userID+"\" width=\"50\">");
	// Profile home page URL
	$("#profileurl").empty();
	$("#profileurl").attr("href", "http://"+data.useralias+".sofurry.com").append(data.username);
	
	$("#pmcount").empty();
	$("#pmcount").attr("href", "http://www.sofurry.com/user/pm").append(data.unreadPMCount + " PMs");
	$("#notification_total").empty();
	$("#notification_total").attr("href", "http://www.sofurry.com/user/notification/list").append(data.notificationTotalCount + " notifications");
	$("#profileviews").empty();
	$("#profileviews").append("Profile views:<br>" + formatNumber(data.profileViewCount,0,'.','','','','-',''));
	$("#submissionviews").empty();
	$("#submissionviews").append("Submission views:<br>" + formatNumber(data.submissionViewCount,0,'.','','','','-',''));
	
}

